<template>
  <el-tabs v-model="activeTab">
    <el-tab-pane label="用户列表" name="userList">
      <el-table :data="tableData" style="width: 100%" border empty-text="没有数据">
        <el-table-column width="80" label="序号" prop="id" />
        <el-table-column width="100" label="昵称" prop="nickname" />
        <el-table-column width="100" label="姓名" prop="realName" />
        <el-table-column width="100" label="职位" prop="position" />
        <el-table-column width="120" label="手机号" prop="phone" />
        <el-table-column label="身份证号" prop="idNumber" />
        <el-table-column width="80" label="性别" prop="gender"/>
        <el-table-column width="80" label="积分" prop="points" />
        <el-table-column width="100" label="预约权限" >
          <template #default="{ row }">
            <el-tag type="success" v-if="row['reservationPermission']">有</el-tag>
            <el-tag type="danger" v-else>无</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createAt" />
        <el-table-column width="140" align="right" fixed="right" >
          <template #header>
            <el-input v-model="search" @input="() => { userPage = 1; loadUsers() }" size="small" placeholder="搜索姓名" />
          </template>
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
<!--            <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="userPage"
          :page-size="userPageSize"
          :total="userTotal"
          @current-change="loadUsers"
          layout="total, prev, pager, next"
          background
          style="margin-top: 16px"
      />

    </el-tab-pane>

    <el-tab-pane label="预约权限审核" name="review">
      <el-table :data="filteredReviewUsers" style="width: 100%" border empty-text="没有待审核">
        <el-table-column width="80" label="序号" prop="id" />
        <el-table-column width="100" label="姓名" prop="realName" />
        <el-table-column width="120" label="手机号" prop="phone" />
        <el-table-column label="身份证号" prop="idNumber" />
        <el-table-column width="80" label="性别" :formatter="row => row.gender ? '男' : '女'" />
        <el-table-column width="80" label="积分" prop="points" />
        <el-table-column label="创建时间" prop="createAt" />
        <el-table-column label="操作" width="180">
          <template #header>
            <el-input v-model="search" @input="loadReviewUsers" size="small" placeholder="搜索姓名" />
          </template>
          <template #default="scope">
            <el-button size="small" type="success" @click="approveUser(scope.row)">通过</el-button>
            <el-button size="small" type="danger" @click="rejectUser(scope.row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          @current-change="loadReviewUsers"
          layout="total, prev, pager, next"
          background
          style="margin-top: 16px"
      />
    </el-tab-pane>
  </el-tabs>

  <CreateUserDialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :userData="selectedUser"
      @submit="handleSubmit"
  />
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import {
  getUsers,
  createUser,
  getNotReviewUsers,
  approveUserApi,
  rejectUserApi,
  updateUser
} from '../utils/userApi'
import CreateUserDialog from '@/apps/admin/components/CreateUserDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户类型声明
interface User {
  id: number
  realName: string
  phone: string
  idNumber: string
  gender: boolean
  points: number
  reservationPermission: boolean
  isActive: boolean
  position: string
  createAt: string
}

const activeTab = ref<'userList' | 'review'>('userList')
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const selectedUser = ref<User | Record<string, never>>({})

const search = ref('')

const tableData = ref<User[]>([])
const reviewUsers = ref<User[]>([])

const page = ref(1)
const pageSize = 10
const total = ref(0)

const userPage = ref(1)
const userPageSize = 10
const userTotal = ref(0)


const loadUsers = (): void => {
  getUsers(userPage.value, userPageSize, search.value)
      .then(res => {
        tableData.value = res.data?.users || []
        userTotal.value = res.data?.total || 0
      })
      .catch(() => {
        ElMessage.error('加载用户失败')
      })
}


const loadReviewUsers = (): void => {
  getNotReviewUsers(page.value, pageSize)
      .then(res => {
        reviewUsers.value = res.data?.users || []
        total.value = res.data?.total || 0
      })
      .catch(() => {
        ElMessage.error('加载审核用户失败')
      })
}

const filteredReviewUsers = computed(() =>
    reviewUsers.value.filter(u =>
        !search.value || u.realName.toLowerCase().includes(search.value.toLowerCase())
    )
)

const openCreateDialog = (): void => {
  dialogMode.value = 'create'
  selectedUser.value = {}
  dialogVisible.value = true
}

const editUser = (user: User): void => {
  console.log(user)
  dialogMode.value = 'edit'
  selectedUser.value = { ...user }
  dialogVisible.value = true
}

const deleteUser = (user: User): void => {
  ElMessageBox.confirm(`确定删除用户 ${user.realName} 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {

        ElMessage.success('删除成功')
        loadUsers()
      })
      .catch(() => {})
}

 const handleSubmit = async (user: User) => {
  let res : any;
  try {
    if (dialogMode.value == 'edit') {
      res = await updateUser(user)
    } else {
      res = await createUser(user)
    }
  } catch(err) {
     ElMessage.error(err.response?.data?.msg || '操作失败')
  }

   if (res.code === 200) {
     ElMessage.success('操作成功')
     dialogVisible.value = false
     loadUsers()
   } else {
     ElMessage.error(res.msg)
   }

}

const approveUser = (user: User): void => {
  ElMessageBox.confirm(`确认通过用户 ${user.realName} 的预约权限？`, '审核确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    approveUserApi(user.id).then(() => {
      ElMessage.success('审核通过')
      loadReviewUsers()
      loadUsers()
    })
  }).catch(() => {})
}

const rejectUser = (user: User): void => {
  ElMessageBox.confirm(`确认拒绝用户 ${user.realName} 的预约权限？`, '审核确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    rejectUserApi(user.id).then(() => {
      ElMessage.success('已拒绝')
      loadReviewUsers()
      loadUsers()
    })
  }).catch(() => {})
}

// 初始加载
loadUsers()
loadReviewUsers()
</script>
